import { Inject, Provide } from '@midwayjs/core';
import { Context } from '@midwayjs/koa';
import { InjectEntityModel } from "@midwayjs/typeorm";
import { Repository } from "typeorm";
import { OnlineEntity } from "@entity/monitor/online.entity";
import { ListOnlineDTO } from "@dto/monitor/online.dto";
import { resBuild } from "@utils/resBuild";

@Provide()
export class OnlineService {
  @Inject()
  ctx: Context;

  @InjectEntityModel(OnlineEntity)
  onlineEntity: Repository<OnlineEntity>;

  // 列表
  async list(queryParams: ListOnlineDTO) {
    const queryBuilder = this.onlineEntity.createQueryBuilder('entity');
    if(queryParams.ipaddr) {
      queryBuilder.andWhere(`entity.ipaddr like "%${queryParams.ipaddr}%"`)
    }
    if(queryParams.userName) {
      queryBuilder.andWhere(`entity.userName like "%${queryParams.userName}%"`)
    }
    if(queryParams.pageNum && queryParams.pageSize) {
      queryBuilder.skip((queryParams.pageNum - 1) * queryParams.pageSize).take(queryParams.pageSize)
    }
    const [rows, total] = await queryBuilder.getManyAndCount()
    return resBuild.list(rows, total)
  }
}
